package com.rep.core;

import com.rep.core.config.TableConfiguration;
import com.rep.core.parse.DefaultReplicationParse;
import com.rep.core.parse.ReplicationParse;
import com.rep.core.parse.model.Configuration;
import com.rep.core.parse.model.Tables;
import com.rep.core.query.DataQuery;
import com.rep.core.replace.CustomRepField;
import com.rep.core.replace.RepFieldService;
import com.rep.core.repository.DataOperation;
import com.rep.core.sql.CreateInsertSql;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wangye
 * @classname DataReplication
 * @date 2020/9/25 15:52
 **/
@Component
public class DataReplication {

    private final static Map<String, Class> ENTITY_CLASS_MAP = new ConcurrentHashMap<>();

    @Autowired
    private DataQuery dataQuery;
    @Autowired
    private RepFieldService repFieldService;
    @Autowired(required = false)
    private CustomRepField customRepField;
    @Autowired
    private CreateInsertSql createInsertSql;
    @Autowired
    private DataOperation dataOperation;
    @Autowired
    private TableConfiguration tableConfiguration;
    @Autowired(required = false)
    private ReplicationParse replicationParse;


    private void setIsMapUnderScoreToCamleCase(Tables tables) {
        Configuration configuration = tables.getConfiguration();
        tableConfiguration.isMapUnderscoreToCamelCase = "true".equals(configuration.getFieldNamePattern().getIsCamelCase());
    }


    public void copy(Map<String, Object> param, String filePath) throws Exception {

        replicationParse = replicationParse == null ? new DefaultReplicationParse() : replicationParse;
        //查询要复制的数据
        Tables tables = ReplicationParse.TABLES_MAP.get(filePath);
        if (tables == null) {
            tables = replicationParse.loadConfig(filePath);
            ReplicationParse.TABLES_MAP.put(filePath, tables);
        }
        setIsMapUnderScoreToCamleCase(tables);
        if (tables == null) {
            tables = replicationParse.loadConfig(filePath);
            ReplicationParse.TABLES_MAP.put(filePath, tables);
        }

        Map<String, List<Map>> dataMap = dataQuery.queryData(param, tables);
        //对外开发接口自定义修改数据
        if (customRepField != null) {
            customRepField.beforeReplace(dataMap);
        }

        //替换关联关系字段并根据配置策略替换指定字段
        repFieldService.replace(dataMap, tables, param);

        //对外开发接口自定义修改数据
        if (customRepField != null) {
            customRepField.afterReplace(dataMap);
        }

        //生成insert语句
        List<String> insertSql = createInsertSql.createInsertSql(dataMap, tables);
        //保存数据
        for (String sql : insertSql) {
            dataOperation.insert(sql);
        }
    }


}
